<template>
  <div class="frame">
    <el-card v-for="(idea, index) in paginatedIdeas" :key="idea.id" class="idea-card">
      <div class="idea-title">
        <router-link :to="`/idea?id=${idea.id}`" class="title-url">{{ idea.title }}</router-link>
      </div>
      <div class="idea-meta">
        <div class="left-info">
          <span class="info-item">{{ idea.created_at }}</span>
          <div class="idea-tags">
            <el-tag
              v-for="tag in idea.tags"
              :key="tag"
              size="small"
              effect="light"
              @click="handleTagClick(tag)"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
        <div class="right-info">
          <el-icon class="icon-view">
            <View />
          </el-icon>
          <span class="info-item">浏览-{{ idea.views }}</span>
          <el-divider
            class="el-divider-vertical"
            direction="vertical"
          ></el-divider>
          <el-icon class="icon-star">
            <StarFilled />
          </el-icon>
          <span class="info-item">赞-{{ idea.stars }}</span>
        </div>
      </div>
      
      <div class="idea-content">
        <p class="content-text">{{ idea.content }}</p>
      </div>
    </el-card>
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        :page-count="totalPages"
        @size-change="handleSizeChange"
        @onUpdate:currentPage="handleUpdateCurrentPage(currentPage)"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { apiGetIdeas } from '@/api/idea';
import type { Idea, IdeasResponse } from "@/types/idea";
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();
const router = useRouter();

// 分页参数
let currentPage = ref(1); // 当前页码
let pageSize = ref(10);
let totalPages = ref(0);

let ideaList = ref<Idea[]>([]);
let ideaCount = 0; // 当前页面获取到的idea数目
let lastIdeaId = 0;
let lastIdeaIdTemp = 0;

// 计算当前页面显示的博客，computed 作用
// 自动更新: 当 computed 依赖的数据发生变化时，它会自动重新计算。
// 缓存结果: computed 会在其依赖未发生变化时缓存结果，避免不必要的计算
let paginatedIdeas = computed(() => {
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + ideaCount;
    lastIdeaIdTemp = lastIdeaId;
    lastIdeaId = ideaList.value[endIndex - 1]?.id || 0;
    return ideaList.value.slice(startIndex, endIndex);
});

// 处理分页变化
async function handleCurrentChange(ideaId: number, count: number) {
    // 假设需要执行其他操作，如重新获取数据并更新 UI
    try {
        const rsp: IdeasResponse = await apiGetIdeas(ideaId, count)
        if (rsp.idea_count > 0) {
            ideaList.value = rsp.ideas;
            ideaCount = rsp.idea_count;
            totalPages.value = (rsp.total_count + pageSize.value - 1) / pageSize.value;
        }
    }
    catch (err) {
        alert(err);
    }
}

// 页面加载时获取第一页的博客
onMounted(() => {
  if (!userStore.isLogin) {
    ElMessage.error("请先登录");
    router.push("/login");
  } else {
    handleCurrentChange(0, pageSize.value);
  }
});

function handleTagClick(tag: string) {
    alert("Handle Tag Click: " + tag);
}

function handleSizeChange(newSize: number) {
    pageSize.value = newSize;
    handleCurrentChange(lastIdeaIdTemp, pageSize.value);
}

function handleUpdateCurrentPage(newPage: number) {
    alert("Handle Update Current Page")
    currentPage.value = newPage;
    handleCurrentChange(lastIdeaId, pageSize.value);
}

</script>

<style scoped>

.frame {
  /* min-height: 100vh; */
  /* display: flex; */
  display: block;
  width: 80%;
  margin-left: 10%;
  margin-top: 1%;
}

@media (max-width: 1024px) {
  .frame {
    width: 100%;
    margin-left: 0;
  };
}

.idea-card {
  margin-bottom: 2px;
  border-radius: 15%;
  background-color: #f3f1f1;
}

.idea-title {
  margin-bottom: 10px;
}

.title-url {
  font-size: 20px; /* 调整标题字体大小 */
  color: #333;
  text-decoration: none;
}

.idea-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

.left-info {
  display: flex;
  align-items: center;
}

.right-info {
  display: flex;
  align-items: center;
}

.info-item {
  margin-left: 10px; /* 增加元素之间的间距 */
}

.content-text {
  font-size: 14px; /* 调整内容字体大小 */
  color: #666;
  margin-top: 10px;
}

.idea-list-container {
  display: flex;
  flex-direction: column;
  gap: 10px; /* 控制博客卡片之间的间距 */
}

.pagination-container {
  display: flex;
  justify-content: flex-end; /* 使页码靠右显示 */
}

.idea-tags {
  margin: 6px 6px; /* 为标签添加间距 */
}

/* 垂直分割线 */
.el-divider-vertical {
  margin: 0 5px; /* 增加分割线的间距 */
}

</style>
